<template>
  <div class="app-container">
    <t-row :gutter="20">
      <!--部门数据-->
      <t-col :lg="2" :xs="12">
        <div class="head-container">
          <t-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            style="margin-bottom: 20px"
          >
            <template #prefix-icon>
              <t-icon name="search" />
            </template>
          </t-input>
        </div>
        <div class="head-container">
          <t-tree
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter="filterNode"
            ref="deptTreeRef"
            v-model:actived="currentNode"
            expand-all
            activable
            @click="handleNodeClick"
          />
        </div>
      </t-col>
      <!--用户数据-->
      <t-col :lg="10" :xs="12">
        <t-form
          :data="queryParams"
          ref="queryRef"
          layout="inline"
          v-show="showSearch"
          label-width="68px"
          class="mb20"
        >
          <t-form-item label="用户名称" name="userName">
            <t-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @enter="handleQuery"
            />
          </t-form-item>
          <t-form-item label="手机号码" name="phonenumber">
            <t-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @enter="handleQuery"
            />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <t-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="创建时间" style="width: 308px">
            <t-date-range-picker v-model="dateRange" allow-input clearable />
          </t-form-item>
          <t-form-item>
            <t-space>
              <t-button theme="primary" @click="handleQuery">
                搜索
                <template #icon>
                  <t-icon name="search" />
                </template>
              </t-button>
              <t-button theme="default" @click="resetQuery">
                重置
                <template #icon>
                  <t-icon name="refresh" />
                </template>
              </t-button>
            </t-space>
          </t-form-item>
        </t-form>

        <t-row :gutter="10" class="mb8">
          <t-col :span="1.5">
            <t-button
              theme="primary"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增
              <template #icon>
                <t-icon name="add" />
              </template>
            </t-button>
          </t-col>
          <t-col :span="1.5">
            <t-button
              theme="success"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
              >修改

              <template #icon>
                <t-icon name="edit" />
              </template>
            </t-button>
          </t-col>
          <t-col :span="1.5">
            <t-button
              theme="danger"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除
              <template #icon>
                <t-icon name="delete" />
              </template>
            </t-button>
          </t-col>
          <t-col :span="1.5">
            <t-button
              theme="default"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >导入
              <template #icon>
                <t-icon name="upload" />
              </template>
            </t-button>
          </t-col>
          <t-col :span="1.5">
            <t-button
              theme="warning"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出
              <template #icon>
                <t-icon name="download" />
              </template>
            </t-button>
          </t-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
            v-model:showColumn="columnControllerVisible"
          ></right-toolbar>
        </t-row>

        <t-table
          v-loading="loading"
          row-key="userId"
          :data="userList"
          :columns="columns"
          :selected-row-keys="ids"
          @select-change="handleSelectionChange"
          v-model:displayColumns="displayColumns"
          v-model:columnControllerVisible="columnControllerVisible"
          :column-controller="{
            fields: [
              'userId',
              'userName',
              'nickName',
              'dept.deptName',
              'phonenumber',
              'status',
              'createTime',
            ],
            dialogProps: { preventScrollThrough: true },
            hideTriggerButton: true,
          }"
        >
          <template #status="{ row }">
            <t-switch
              v-model="row.status"
              :customValue="['0', '1']"
              @change="handleStatusChange(row)"
            ></t-switch>
          </template>
          <template #createTime="{ row }">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>

          <template #action="{ row }">
            <t-tooltip content="修改" placement="top" v-if="row.userId !== 1">
              <t-button
                variant="text"
                theme="primary"
                @click="handleUpdate(row)"
                v-hasPermi="['system:user:edit']"
              >
                <template #icon>
                  <t-icon name="edit" />
                </template>
              </t-button>
            </t-tooltip>
            <t-tooltip content="删除" placement="top" v-if="row.userId !== 1">
              <t-button
                variant="text"
                theme="primary"
                @click="handleDelete(row)"
                v-hasPermi="['system:user:remove']"
              >
                <template #icon>
                  <t-icon name="delete" />
                </template>
              </t-button>
            </t-tooltip>
            <t-tooltip
              content="重置密码"
              placement="top"
              v-if="row.userId !== 1"
            >
              <t-button
                variant="text"
                theme="primary"
                @click="handleResetPwd(row)"
                v-hasPermi="['system:user:resetPwd']"
              >
                <template #icon>
                  <t-icon name="lock-off" />
                </template>
              </t-button>
            </t-tooltip>
            <t-tooltip
              content="分配角色"
              placement="top"
              v-if="row.userId !== 1"
            >
              <t-button
                variant="text"
                theme="primary"
                @click="handleAuthRole(row)"
                v-hasPermi="['system:user:edit']"
              >
                <template #icon>
                  <t-icon name="check-circle" />
                </template>
              </t-button>
            </t-tooltip>
          </template>
        </t-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </t-col>
    </t-row>

    <!-- 添加或修改用户配置对话框 -->
    <t-dialog :title="title" v-model:visible="open" width="600px" attach="body">
      <t-form :data="form" :rules="rules" ref="userRef" label-width="80px">
        <t-row class="mb10">
          <t-col :span="6">
            <t-form-item label="用户昵称" prop="nickName">
              <t-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                :maxlength="30"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="归属部门" prop="deptId">
              <t-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                clearable
                placeholder="请选择归属部门"
                :tree-props="{
                  keys: {
                    label: 'label',
                    value: 'id',
                    children: 'children',
                  },
                }"
              />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row class="mb10">
          <t-col :span="6">
            <t-form-item label="手机号码" prop="phonenumber">
              <t-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                :maxlength="11"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="邮箱" prop="email">
              <t-input
                v-model="form.email"
                placeholder="请输入邮箱"
                :maxlength="50"
              />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row class="mb10">
          <t-col :span="6">
            <t-form-item
              v-if="form.userId == undefined"
              label="用户名称"
              prop="userName"
            >
              <t-input
                v-model="form.userName"
                placeholder="请输入用户名称"
                :maxlength="30"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item
              v-if="form.userId == undefined"
              label="用户密码"
              prop="password"
            >
              <t-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                :maxlength="20"
                show-password
              />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row class="mb10">
          <t-col :span="6">
            <t-form-item label="用户性别">
              <t-select v-model="form.sex" placeholder="请选择">
                <t-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></t-option>
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="状态">
              <t-radio-group v-model="form.status">
                <t-radio
                  v-for="dict in sys_normal_disable"
                  :value="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</t-radio
                >
              </t-radio-group>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row class="mb10">
          <t-col :span="6">
            <t-form-item label="岗位">
              <t-select v-model="form.postIds" multiple placeholder="请选择">
                <t-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></t-option>
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="角色">
              <t-select v-model="form.roleIds" multiple placeholder="请选择">
                <t-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></t-option>
              </t-select>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row class="mb10">
          <t-col :span="12">
            <t-form-item label="备注">
              <t-textarea
                v-model="form.remark"
                placeholder="请输入内容"
              ></t-textarea>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitForm">确 定</t-button>
          <t-button theme="default" @click="cancel">取 消</t-button>
        </div>
      </template>
    </t-dialog>

    <!-- 用户导入对话框 -->
    <t-dialog
      :title="upload.title"
      v-model:visible="upload.open"
      width="410px"
      attach="body"
    >
      <t-upload
        ref="uploadRef"
        :max="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        theme="custom"
        v-model="upload.fileList"
        :format-response="formatResponse"
        draggable
      >
        <template #dragContent="params">
          <ul
            v-if="upload.fileList && upload.fileList.length"
            style="padding: 0"
          >
            <li
              v-for="file in upload.fileList"
              :key="file.name"
              style="list-style-type: none"
            >
              {{ file.name }}
            </li>
          </ul>
          <template v-else>
            <p v-if="params && params.dragActive">释放鼠标</p>
            将文件拖到此处，或<em>点击上传</em>
            <!-- <t-button v-else-if="progress < 1">自定义拖拽区域</t-button> -->
          </template>
          <t-button
            v-if="upload.fileList && upload.fileList.length"
            size="small"
            style="margin-top: 36px"
            >更换文件</t-button
          >
          <!-- <span>数据状态：{{params}}</span> -->
        </template>
        <template #tips>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <t-checkbox v-model="upload.updateSupport">
                是否更新已经存在的用户数据</t-checkbox
              >
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <t-link
              theme="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</t-link
            >
          </div>
        </template>
      </t-upload>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitFileForm">确 定</t-button>
          <t-button theme="default" @click="upload.open = false"
            >取 消</t-button
          >
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  fileList: [],
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
});
const staticColumn = ["row-select", "action"];

const displayColumns = ref(
  staticColumn.concat([
    "userId",
    "userName",
    "nickName",
    "dept.deptName",
    "phonenumber",
    "status",
    "createTime",
  ])
);
const columnControllerVisible = ref(false);

const columns = ref([
  {
    colKey: "row-select",
    type: "multiple",
    title: "选择",
    width: 50,
  },
  { colKey: "userId", title: "用户编号", width: "100" },
  { colKey: "userName", title: "用户名称", ellipsis: true },
  { colKey: "nickName", title: "用户昵称", ellipsis: true },
  { colKey: "dept.deptName", title: "部门", ellipsis: true },
  { colKey: "phonenumber", title: "手机号" },
  { colKey: "status", title: "状态" },
  { colKey: "createTime", title: "创建时间" },
  { colKey: "action", title: "操作" },
]);

const userRef = ref(null);
const uploadRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
  },
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = ref(null);
/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  filterNode.value = (node) => node.data.label.indexOf(val) >= 0;
});
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      userList.value = res.rows;
      total.value = res.total;
    }
  );
}
const currentNode = ref([]);
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.node.data.id;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  if (currentNode && currentNode.value) {
    currentNode.value.forEach((item) => {
      proxy.$refs.deptTreeRef.setItem(item, { actived: false });
    });
  }
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}
/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
}
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}
/** 选择条数  */
const handleSelectionChange = (selectedRowKeys, { selectedRowData }) => {
  ids.value = selectedRowKeys;
  single.value = selectedRowData.length != 1;
  multiple.value = !selectedRowData.length;
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/user/importTemplate",
    {},
    `user_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

const formatResponse = (res) => {
  console.log(res);
  if (res.code == 500) {
    proxy.$modal.msgError(res.msg);
    return {
      error: res.msg,
    };
  }
  return {
    url: res.msg,
  };
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log(response);
  upload.open = false;
  upload.isUploading = false;
  upload.fileList = [];
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
const submitFileForm = () => {
  uploadRef.value.uploadFiles();
};
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  getUser().then((response) => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.userId || ids.value;
  getUser(userId).then((response) => {
    form.value = response.data;
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    form.value.postIds = response.postIds;
    form.value.roleIds = response.roleIds;
    open.value = true;
    title.value = "修改用户";
    form.password = "";
  });
}
/** 提交按钮 */
const submitForm = () => {
  userRef.value.validate().then((valid) => {
    if (valid == true) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

getDeptTree();
getList();
</script>
